package com.quanquan.user.controller;


import DTO.PageDTO;
import DTO.user.ExportUserDto;
import base.BaseController;
import com.alibaba.fastjson.JSONArray;
import com.quanquan.user.service.autoCompute.dto.PushStatusDTO;
import com.quanquan.user.service.autoCompute.entity.LabelGroup;
import com.quanquan.user.service.autoCompute.entity.LabelGroupSynRecord;
import com.quanquan.user.service.autoCompute.request.LabelGroupRequestBody;
import com.quanquan.user.service.autoCompute.request.PushCouponRequestBody;
import com.quanquan.user.service.autoCompute.service.LabelGroupService;
import com.quanquan.user.service.autoCompute.service.SynRecordService;
import enums.ResCodeEnum;
import exceptions.service.ServiceRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;
import utils.ReadAndWriteJson;
import web.response.ResultBody;

import javax.servlet.http.HttpServletResponse;
import java.util.LinkedList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/labelGroup")
public class LabelGroupController extends BaseController {

    @Autowired
    private LabelGroupService labelGroupService;

    @Autowired
    private SynRecordService synRecordService;

    @Value("${user-label.path}")
    private String userLabelFilePath;

    /**
     * 创建用户画像
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/create")
    public ResultBody create(@RequestBody LabelGroupRequestBody requestBody) {
        try {
            LabelGroup labelGroup = labelGroupService.create(requestBody);
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), labelGroup);
        } catch (ServiceRuntimeException e) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(), e.getMessage());
        }
    }

    /**
     * 分页获取画像
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/list")
    public ResultBody list(@RequestBody LabelGroupRequestBody requestBody) {
        try {
            PageDTO<LabelGroup> result = labelGroupService.list(requestBody);
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), result);
        } catch (Exception e) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(), e.getMessage());
        }
    }

    /**
     * 根据Id获取用户画像
     *
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    public ResultBody getOne(@PathVariable String id) {
        try {
            LabelGroup byId = labelGroupService.getById(id);
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), byId);
        } catch (ServiceRuntimeException e) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(), e.getMessage());
        }
    }

    @GetMapping("/get")
    public ResultBody get(@RequestParam String id) {
        try {
            LabelGroup byId = labelGroupService.getSimple(id);
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), byId);
        } catch (ServiceRuntimeException e) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(), e.getMessage());
        }
    }

    /**
     * 修改画像
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/update")
    public ResultBody update(@RequestBody LabelGroupRequestBody requestBody) {
        try {
            LabelGroup update = labelGroupService.update(requestBody);
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), update);
        } catch (ServiceRuntimeException e) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(), e.getMessage());
        }
    }

    /**
     * 删除画像
     *
     * @param id
     * @return
     */
    @GetMapping("/remove/{id}")
    public ResultBody remove(@PathVariable String id) {
        try {
            labelGroupService.remove(id);
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg());
        } catch (ServiceRuntimeException e) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(), ResCodeEnum.FAIL.getMsg());
        }
    }

    /**
     * 手动同步标签分组
     *
     * @param id
     * @return
     */
    @GetMapping("/sync/{id}")
    public ResultBody syncLabelGroup(@PathVariable String id) {
        try {
            LabelGroup labelGroup = labelGroupService.syncLabelGroup(id);
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), labelGroup);
        } catch (ServiceRuntimeException e) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(), e.getMessage());
        }
    }

    @PostMapping("/push")
    public ResultBody pushCoupon(@RequestBody PushCouponRequestBody requestBody) {
        try {
            labelGroupService.pushCoupon(requestBody);
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg());
        } catch (ServiceRuntimeException e) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(), e.getMessage());
        }
    }

    @GetMapping("/pushStatus")
    public ResultBody pushStatus(String id) {
        PushStatusDTO dto = labelGroupService.pushStatus(id);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), dto);
    }


    /**
     * 分页获取同步记录
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/synRecordList/{id}")
    public ResultBody synRecordList(@RequestBody LabelGroupRequestBody requestBody, @PathVariable String id) {
        try {
            PageDTO<LabelGroupSynRecord> result = synRecordService.list(requestBody,id);
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), result);
        } catch (Exception e) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(), e.getMessage());
        }
    }

    @PostMapping("/synRecordDetail")
    public ResultBody synRecordDetail(String groupId, String id) {
        try {
            String file = new StringBuffer().append(userLabelFilePath)
                    .append("synRecord_")
                    .append(groupId).append("_")
                    .append(id).append(".json").toString();
            String readFile = ReadAndWriteJson.readFile(file);
            List<Object> list = JSONArray.parseArray(readFile, Object.class);

            List<ExportUserDto> rows = new LinkedList<>();
            list.forEach(dto -> {
                List<String> strings = JSONArray.parseArray(dto.toString(), String.class);
                ExportUserDto exportUserDto = new ExportUserDto();
                exportUserDto.setUserId(strings.get(0));
                exportUserDto.setPhone(strings.get(1));
                exportUserDto.setName(strings.get(2));
                exportUserDto.setCard(strings.get(3));
                if(strings.get(4).equals("0")){
                    exportUserDto.setGender("男");
                }else if(strings.get(4).equals("1")){
                    exportUserDto.setGender("女");
                }else{
                    exportUserDto.setGender("保密");
                }
                exportUserDto.setAge(strings.get(5));
                exportUserDto.setBirthday(strings.get(6));
                exportUserDto.setCreateTime(strings.get(7));
                rows.add(exportUserDto);
            });

            PageDTO<ExportUserDto> pageResult = new PageDTO<>();
            pageResult.setTotal((long) rows.size());
            pageResult.setList(rows);

            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), pageResult);
        } catch (Exception e) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(), e.getMessage());
        }
    }

    @GetMapping("/exportData")
    public void exportData(HttpServletResponse response,String groupId, Long id){
        try {
            String file = new StringBuffer().append(userLabelFilePath)
                    .append("synRecord_")
                    .append(groupId).append("_")
                    .append(id).append(".json").toString();
            String readFile = ReadAndWriteJson.readFile(file);
            List<Object> list = JSONArray.parseArray(readFile, Object.class);

            String fileName = System.currentTimeMillis()+".csv";
            response.setHeader("Content-type", "text/csv; charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\";charset=utf-8");

            String[] titles = {"手机号","姓名","卡号","性别","年龄","生日","注册时间"};
            String[] field = {"phone","name","card","gender","age","birthday","createTime"};

            List<ExportUserDto> rows = new LinkedList<>();
            list.forEach(dto -> {
                List<String> strings = JSONArray.parseArray(dto.toString(), String.class);
                ExportUserDto exportUserDto = new ExportUserDto();
                exportUserDto.setPhone(strings.get(1));
                exportUserDto.setName(strings.get(2));
                exportUserDto.setCard(strings.get(3));
                if(strings.get(4).equals("0")){
                    exportUserDto.setGender("男");
                }else if(strings.get(4).equals("1")){
                    exportUserDto.setGender("女");
                }else{
                    exportUserDto.setGender("保密");
                }
                exportUserDto.setAge(strings.get(5));
                exportUserDto.setBirthday(strings.get(6));
                exportUserDto.setCreateTime(strings.get(7));
                rows.add(exportUserDto);
            });

            ICsvBeanWriter csvBeanWriter = new CsvBeanWriter(response.getWriter(), CsvPreference.STANDARD_PREFERENCE);
            csvBeanWriter.writeHeader(titles);
            for (ExportUserDto exportUserDto:rows){
                csvBeanWriter.write(exportUserDto,field);
            }
            csvBeanWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
